/*
 * @Author: chunlai
 * @Date: 2025-04-10 08:23:49
 * @LastEditTime: 2025-07-16 13:40:51
 * @LastEditors: minsheng_insurance_agency_zhoucl
 * @FilePath: \02.bldinsure\src\utils\request.js
 * @Description:
 */
import axios from "axios";
import qs from "qs";
import { Toast, Dialog } from "vant";
import store from "../store/index";

// create an axios instance
const service = axios.create({
  baseURL: `${process.env.VUE_APP_API}`,
  timeout: 600000,
  //转换数据的方法
  showDialog: true,
});

service.interceptors.request.use(
  (config) => {
    if (config.url.indexOf(".json") == -1) {
      config.headers["request-startTime"] = new Date().getTime();
      config.headers["Content-Type"] =
        "application/x-www-form-urlencoded;charset=UTF-8";
    }
    if (config.json) {
      config.headers["Content-Type"] = "application/json";
    }

    if (
      config.headers["Content-Type"] ==
      "application/x-www-form-urlencoded;charset=UTF-8"
    ) {
      config.data = qs.stringify(config.data);
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    let { config } = response;
    // 记录接口响应时间
    if (process.env.VUE_APP_PRODFLAG === "tps") {
      if (response.config.method == "post" && response.status == 200) {
      }
    }
    const res = response.data;
    // 对结果进行拦截 result === "1"放行
    if (res.result && res.result != "1") {
      if (config.showDialog) {
        Dialog.alert({
          title: "温馨提示",
          message: res.message,
        }).then(() => {});
      }
      store.commit("updateLoad", false);
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    let errTip = "系统错误，请联系管理员";
    console.log(error);
    if (error.response) {
      if (error.response.status) {
        switch (error.response.status) {
          case 404:
            errTip = "请求错误,未找到该资源-404";
            break;
          case 408:
            errTip = "请求超时";
            break;
          case 500:
            errTip = "服务器异常";
            break;
          default:
            errTip = "请求异常-" + error.response.status;
            break;
        }
      }
      let { config } = error.response;
      if (config && config.showDialog) {
        Toast({
          message: errTip,
          duration: 5 * 1000,
        });
      }
    }

    return Promise.reject(errTip);
  }
);

export default service;
